package ext.acae2.dms.web.input;

import java.io.File;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.log4j.Logger;

import wt.log4j.LogR;
import wt.pom.Transaction;

public class SubmitProcessor {

    private static final Logger LOGGER = LogR.getLogger(SubmitProcessor.class.getName());
    
    public String process(HttpServletRequest request) {
        LOGGER.debug("> Start process");
        
        Transaction trans = new Transaction();
	Map<String, String> map = null;
        
        try {
            trans.start();
            List<DiskFileItem> parameters = new WebUtil().parseRequest(request);
            LOGGER.debug("parameters: " + parameters.size());
            
            String supplier = new WebUtil().getSupplierName(parameters);
            LOGGER.debug("supplier: " + supplier);
            
            //1. Upload file to server.
            LOGGER.debug("---------- Step 1 start ----------");
            File serverFile = new UploadFileProcessor().upload(parameters);
            LOGGER.debug("---------- Step 1 end ----------");
            
            //2. Create WTDocument on Windchill side.
            LOGGER.debug("---------- Step 2 start ----------");
            map = new DocumentProcessor().create(serverFile, supplier);
            LOGGER.debug("---------- Step 2 end ----------");
            
            trans.commit();
        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            trans.rollback();
            return "error";
        }
        
        LOGGER.debug("> End process");
        return map.get("number") + "," + map.get("path");
    }
}
